<?php

namespace App\Service\Activity;

use App\Http\Resources\Activity\B\ActivityDataListResource;
use App\Models\Activity\ActivityModel;
use App\Models\Activity\ActivityShopJoinModel;
use App\Models\Activity\ActivityShopRelModel;
use App\Models\Activity\ShopOrderActivityModel;
use App\Models\BaseModel;
use App\Models\Shop\ShopModel;
use App\Service\BaseService;
use Illuminate\Database\Eloquent\Builder;

class ActivityDataService extends BaseService
{

    /**
     * @param object $params
     * @return array|Builder|mixed
     */
    public static function joinStatistics(object $params)
    {
        $paginate = ActivityModel::query()
                                 ->when(checkFieldLen($params, "actionName"), function ($query) use ($params) {
                                     $query->whereHas("actionRel", function ($query) use ($params) {
                                         $query->where("name", "like", "%{$params->actionName}%");
                                     });
                                 })
                                 ->when(checkFieldLen($params, "id"), function ($query) use ($params) {
                                     $query->where("id", $params->id);
                                 })
                                 ->when(checkFieldLen($params, "name"), function ($query) use ($params) {
                                     $query->where("name", "like", "%{$params->name}%");
                                 })
                                 ->when(checkFieldLen($params, "activityType"), function ($query) use ($params) {
                                     $query->where("activityType", $params->activityType);
                                 })
                                ->when(checkFieldLen($params, "status"), function ($query) use ($params) {
                                    $query->where("status", $params->status);
                                })
                                 ->when(checkFieldLen($params, "startTime"), function ($query) use ($params) {
                                     $query->where(function ($query) use ($params) {
                                         $query->where("expireType", ShopOrderActivityModel::EXPIRE_TYPE_0)
                                               ->oRwhere(
                                                   function ($query) use ($params) {
                                                       $query->where("startTime", ">=",
                                                           strtotime($params->startTime))
                                                             ->where("startTime", "<=", strtotime("+1 day",
                                                                     strtotime($params->endTime)) - 1);
                                                   })
                                               ->oRwhere(
                                                   function ($query) use ($params) {
                                                       $query->where("endTime", ">=",
                                                           strtotime($params->startTime))
                                                             ->where("endTime", "<=", strtotime("+1 day",
                                                                     strtotime($params->endTime)) - 1
                                                             );
                                                   })
                                               ->oRwhere(
                                                   function ($query) use ($params) {
                                                       $query->where("endTime", ">=", strtotime("+1 day",
                                                               strtotime($params->endTime)) - 1)
                                                             ->where("startTime", "<=",
                                                                 strtotime($params->startTime));
                                                   }
                                               );
                                     });
                                 })
                                 ->with([
                                     "actionRel" => function ($query) {
                                         $query->select(["id", "name", "activityId", 'goodsNum', 'goodsInfo', 'price', 'originalPrice']);
                                     }
                                 ])
                                 ->withCount("shopRel as canJoinCount")
                                 ->withCount("hasJoinShopRel as hasJoinCount")
                                 ->withCount("stayReviewJoinShopRel as reviewCount")
                                 ->withCount("shopJoinFeedbackRel as feedbackCount")
                                 ->orderByDesc("id")
                                 ->when(
                                     $params->export,
                                     function ($query) {
                                         return $query->get();
                                     },
                                     function ($query) use ($params) {
                                         return $query->paginate($params->pageSize, ['*'], 'pageNum', $params->pageNum);
                                     }
                                 );


        return (bool)$params->export ? $paginate : [
            "list"     => ActivityDataListResource::collection($paginate->items()),
            "count"    => $paginate->total(),
            "pageNum"  => $params->pageNum,
            "pageSize" => $params->pageSize,
        ];
    }

    /**
     * 参与活动门店数据列表 & 导出
     *
     * @param object $params
     * @return array|Builder|mixed
     */
    public static function joinStatisticsShopList(object $params)
    {
        $shopRelClosure = function ($query) use ($params) {
            $query->when($params->export, function ($query) {
                $query->with([
                    "councilorRel" => function ($query) {
                        $query->select(["rmsUserId", "name", "nickname"]);
                    }
                ]);
            })->select(["id", "name", "shopCode", "addressPrefix"]);
        };

        $activityRelClosure = function ($query) {
            $query->select(["id", "name", "activityType"]);
        };

        $activityActionRelClosure = function ($query) {
            $query->select(["id", "name"]);
        };


        switch ($params->businessExportType) {
            // 可参与门店
            case ActivityModel::BUSINESS_EXPORT_TYPE_0:
                $paginate = ShopModel::query()->select(
                    ["id as shopId", "shopCode", "name"]
                )->when(
                    checkFieldLen($params, "shopId"),
                    function ($query) use ($params) {
                        $query->where("id", $params->shopId);
                    }
                )->whereIn(
                    "id",
                    function ($query) use ($params) {
                        $query->select("shopId")
                              ->from((new ActivityShopRelModel())->getTable())
                              ->where("activityId", $params->activityId)
                              ->where("isDeleted", BaseModel::DELETE_NO);
                    }
                )->when(
                    $params->export,
                    function ($query) {
                        return $query->get();
                    },
                    function ($query) use ($params) {
                        return $query->paginate(
                            $params->pageSize, ['*'], 'pageNum', $params->pageNum
                        );
                    }
                );

                $list = (bool)$params->export ? $paginate : collect($paginate->items())->toArray();
                break;
            // 已参与门店
            case ActivityModel::BUSINESS_EXPORT_TYPE_1:
                $paginate = ActivityShopJoinModel::query()
                                                 ->with("shopDetailRel")
                                                 ->where("activityId", $params->activityId)
                                                 ->where("status", ActivityShopJoinModel::STATUS_3)
                                                 ->when(
                                                     checkFieldLen($params, "shopId"),
                                                     function ($query) use ($params) {
                                                         $query->where("shopId", $params->shopId);
                                                     }
                                                 )
                                                 ->when(
                                                     $params->export,
                                                     function ($query) use (
                                                         $activityRelClosure,
                                                         $activityActionRelClosure
                                                     ) {
                                                         return $query->with([
                                                             "activityRel"       => $activityRelClosure,
                                                             "activityActionRel" => $activityActionRelClosure
                                                         ])->get();
                                                     },
                                                     function ($query) use ($params) {
                                                         return $query->paginate(
                                                             $params->pageSize, ['*'], 'pageNum', $params->pageNum
                                                         );
                                                     }
                                                 );

                $list = (bool)$params->export ? $paginate : collect($paginate->items())
                    ->map(function (ActivityShopJoinModel $activityShopJoinModel) {
                        return [
                            "shopId"        => $activityShopJoinModel->shopId,
                            "shopCode"      => attributeGet(
                                $activityShopJoinModel, "shopDetailRel.shopCode", ""
                            ),
                            "name"          => attributeGet($activityShopJoinModel, "shopDetailRel.name", ""),
                            "createdAtText" => $activityShopJoinModel->createdAt->format("Y-m-d H:i:s"),
                        ];
                    })->toArray();
                break;
            // 未参与门店
            case ActivityModel::BUSINESS_EXPORT_TYPE_2:
                $paginate = ActivityShopRelModel::query()
                                                ->with(["shopDetailRel"])
                                                ->where("activityId", $params->activityId)
                                                ->when(
                                                    checkFieldLen($params, "shopId"),
                                                    function ($query) use ($params) {
                                                        $query->where("shopId", $params->shopId);
                                                    }
                                                )
                                                ->whereNotIn("shopId",
                                                    function ($query) use ($params) {
                                                        $query->select("shopId")
                                                              ->from((new ActivityShopJoinModel())->getTable())
                                                              ->where("activityId", $params->activityId)
                                                              ->where("status", ActivityShopJoinModel::STATUS_3)
                                                              ->where("isDeleted", BaseModel::DELETE_NO);
                                                    })
                                                ->when(
                                                    $params->export,
                                                    function ($query) use ($activityRelClosure) {
                                                        return $query->with(["activityRel" => $activityRelClosure])
                                                                     ->get();
                                                    },
                                                    function ($query) use ($params) {
                                                        return $query->paginate(
                                                            $params->pageSize, ['*'], 'pageNum', $params->pageNum
                                                        );
                                                    }
                                                );

                $list = (bool)$params->export ? $paginate : collect($paginate->items())
                    ->map(function (ActivityShopRelModel $activityShopRelModel) {
                        return [
                            "shopId"        => $activityShopRelModel->shopId,
                            "shopCode"      => attributeGet(
                                $activityShopRelModel, "shopDetailRel.shopCode", ""
                            ),
                            "name"          => attributeGet($activityShopRelModel, "shopDetailRel.name", ""),
                            "createdAtText" => $activityShopRelModel->createdAt->format("Y-m-d H:i:s"),
                        ];
                    })->toArray();
                break;
            // 已回传照片
            case ActivityModel::BUSINESS_EXPORT_TYPE_3:
                $paginate = ActivityShopJoinModel::query()
                                                 ->with(["shopDetailRel"])
                                                 ->where("activityId", $params->activityId)
                                                 ->when(
                                                     checkFieldLen($params, "shopId"),
                                                     function ($query) use ($params) {
                                                         $query->where("shopId", $params->shopId);
                                                     }
                                                 )
                                                 ->where("status", ActivityShopJoinModel::STATUS_3)
                                                 ->where("feedbackStatus", ActivityShopJoinModel::FEEDBACK_STATUS_1)
                                                 ->when(
                                                     $params->export,
                                                     function ($query) use (
                                                         $activityRelClosure,
                                                         $activityActionRelClosure
                                                     ) {
                                                         return $query->with([
                                                             "activityRel"       => $activityRelClosure,
                                                             "activityActionRel" => $activityActionRelClosure,
                                                             "joinFeedbackRel"
                                                         ])->get();
                                                     },
                                                     function ($query) use ($params) {
                                                         return $query->paginate(
                                                             $params->pageSize, ['*'], 'pageNum', $params->pageNum
                                                         );
                                                     }
                                                 );

                $list = (bool)$params->export ? $paginate : collect($paginate->items())
                    ->map(function (ActivityShopJoinModel $activityShopJoinModel) {
                        return [
                            "shopId"        => $activityShopJoinModel->shopId,
                            "shopCode"      => attributeGet(
                                $activityShopJoinModel, "shopDetailRel.shopCode", ""
                            ),
                            "name"          => attributeGet($activityShopJoinModel, "shopDetailRel.name", ""),
                            "createdAtText" => $activityShopJoinModel->createdAt->format("Y-m-d H:i:s"),
                        ];
                    })->toArray();
                break;
            // 未回传照片
            case ActivityModel::BUSINESS_EXPORT_TYPE_4:
                $paginate = ActivityShopJoinModel::query()
                                                 ->with("shopDetailRel")
                                                 ->when(
                                                     checkFieldLen($params, "shopId"),
                                                     function ($query) use ($params) {
                                                         $query->where("shopId", $params->shopId);
                                                     }
                                                 )
                                                 ->where("activityId", $params->activityId)
                                                 ->where("status", ActivityShopJoinModel::STATUS_3)
                                                 ->where("feedbackStatus", ActivityShopJoinModel::FEEDBACK_STATUS_0)
                                                 ->when(
                                                     $params->export,
                                                     function ($query) use (
                                                         $activityRelClosure,
                                                         $activityActionRelClosure
                                                     ) {
                                                         return $query->with([
                                                             "activityRel"       => $activityRelClosure,
                                                             "activityActionRel" => $activityActionRelClosure
                                                         ])->get();
                                                     },
                                                     function ($query) use ($params) {
                                                         return $query->paginate(
                                                             $params->pageSize, ['*'], 'pageNum', $params->pageNum
                                                         );
                                                     }
                                                 );

                $list = (bool)$params->export ? $paginate : collect($paginate->items())
                    ->map(function (ActivityShopJoinModel $activityShopJoinModel) {
                        return [
                            "shopId"        => $activityShopJoinModel->shopId,
                            "shopCode"      => attributeGet(
                                $activityShopJoinModel, "shopDetailRel.shopCode", ""
                            ),
                            "name"          => attributeGet($activityShopJoinModel, "shopDetailRel.name", ""),
                            "createdAtText" => $activityShopJoinModel->createdAt->format("Y-m-d H:i:s"),
                        ];
                    })->toArray();
                break;
            // 待审核门店
            case ActivityModel::BUSINESS_EXPORT_TYPE_5:
                $paginate = ActivityShopJoinModel::query()
                                                 ->with(["shopDetailRel"])
                                                 ->where("activityId", $params->activityId)
                                                 ->when(
                                                     checkFieldLen($params, "shopId"),
                                                     function ($query) use ($params) {
                                                         $query->where("shopId", $params->shopId);
                                                     }
                                                 )
                                                 ->where("status", ActivityShopJoinModel::STATUS_1)
                                                 ->when(
                                                     $params->export,
                                                     function ($query) use (
                                                         $activityRelClosure,
                                                         $activityActionRelClosure
                                                     ) {
                                                         return $query->with([
                                                             "activityRel"       => $activityRelClosure,
                                                             "activityActionRel" => $activityActionRelClosure
                                                         ])->get();
                                                     },
                                                     function ($query) use ($params) {
                                                         return $query->paginate(
                                                             $params->pageSize, ['*'], 'pageNum', $params->pageNum
                                                         );
                                                     }
                                                 );

                $list = (bool)$params->export ? $paginate : collect($paginate->items())
                    ->map(function (ActivityShopJoinModel $activityShopJoinModel) {
                        return [
                            "shopId"        => $activityShopJoinModel->shopId,
                            "shopCode"      => attributeGet(
                                $activityShopJoinModel, "shopDetailRel.shopCode", ""
                            ),
                            "name"          => attributeGet($activityShopJoinModel, "shopDetailRel.name", ""),
                            "createdAtText" => $activityShopJoinModel->createdAt->format("Y-m-d H:i:s"),
                        ];
                    })->toArray();
                break;
            case ActivityModel::BUSINESS_EXPORT_TYPE_6:
                $paginate = ActivityShopRelModel::query()
                                                ->where("activityId", $params->activityId)
                                                ->with([
                                                    "activityRel" => $activityRelClosure,
                                                ])->with('shopDetailRel')->get();

                $list = (bool)$params->export ? $paginate : collect($paginate->items())->toArray();
                break;
        }

        return (bool)$params->export ? $list : [
            "list"     => $list,
            "count"    => $paginate->total(),
            "pageNum"  => $params->pageNum,
            "pageSize" => $params->pageSize,
        ];
    }
}
